<template>
  <van-form>
    <van-cell-group inset>
      <van-field
          v-model="newUserData.userAccount"
          name="userAccount"
          required
          label="账号名"
          placeholder="请填写账号(长度不能小于4)"
          :rules="[{ required: true, message: '请填写账号' }]"
      />
      <van-field
          v-model="newUserData.username"
          name="username"
          label="昵称"
          placeholder="给自己取个好听的名字吧"
      />
      <van-field
          v-model="newUserData.profile"
          name="profile"
          label="个性签名"
          placeholder="介绍一下你自己"
      />
      <van-field
          v-model="newUserData.planetCode"
          name="planetCode"
          required
          label="星球编号"
          placeholder="请设置你的星球编号"
          :rules="[{ required: true, message: '请设置星球编号' }]"
      />
      <van-field
          v-model="newUserData.userPassword"
          type="password"
          name="userPassword"
          required
          label="密码"
          placeholder="请输入密码(长度不能小于8)"
          :rules="[{ required: true, message: '请输入密码' }]"
      />
      <van-field
          v-model="newUserData.checkPassword"
          type="password"
          name="checkPassword"
          required
          label="确认密码"
          placeholder="请确认密码"
          :rules="[{ required: true, message: '请确认密码' }]"
      />
    </van-cell-group>
    <van-divider />
    <div style="margin: 16px;" id="registerUserTwoButton">
      <van-button block round type="primary" @click="cancelRegisterUser">
        取消
      </van-button>
      <van-button block round type="primary" @click="doUserRegister">
        注册
      </van-button>
    </div>
  </van-form>
</template>


<script setup lang="ts">
import {useRouter} from "vue-router";
import myAxios from "../plugins/myAxios.ts";
import { ref } from "vue";
import {showSuccessToast, showToast} from "vant";
import {showFailToast} from "vant";

const router = useRouter();

// 新用户默认值
const initNewUser = {
  "userAccount": "",
  "username": "",
  "profile": "",
  "planetCode": "",
  "userPassword": "",
  "checkPassword": "",
}

// 用户填写的注册新用户数据
const newUserData = ref({...initNewUser})

/**
 * 用户注册
 */
const doUserRegister = async () => {
  showToast('正在注册 请稍候...')
  const postData = {
    ...newUserData.value,
  }
  const res = await myAxios.post("/user/register", postData);
  // @ts-ignore
  if(res?.code === 0) {
    showSuccessToast('注册成功');
    router.push({
      path: '/user/login',
      replace: true,
    })
  } else {
    // @ts-ignore
    showFailToast('注册失败' + (res.description ? `${res.description}` : ''));
  }
}

/**
 * 取消注册用户
 */
const cancelRegisterUser = () => {
  showToast('取消注册');
  router.back();
}

</script>


<style scoped>
#registerUserTwoButton {
  display: flex;
  justify-content: center;
}
</style>